import random

import pygame.sprite

from actor import DirWalkByImage, WalkDir

"""
移动战士类
"""


class WalkSoldier(pygame.sprite.Sprite):
    hp = 50
    name = '某军'
    pos_x = 100
    pos_y = 300
    image_width = 50
    image_height = 100

    walk_action = None
    rect = ()

    def __init__(self, walk_path: str, x, y, name, hp):
        """
        参数初始化
        :param walk_path: 图片路径
        :param x:
        :param y:
        :param name:
        :param hp:
        """
        super(WalkSoldier, self).__init__()
        self.walk_action = DirWalkByImage(walk_path, self.image_width,
                                          self.image_height, True)
        self.walk_action.set_dir(WalkDir.down)
        self.cur_dir = WalkDir.down
        self.pos_x = x
        self.pos_y = y
        self.name = name
        self.hp = hp
        self.count = 3
        self.rect = pygame.Rect(x, y, self.image_width, self.image_height)

    def run(self, down_flag, key_list, obstacle_group: pygame.sprite.Group):
        """
        实现移动
        :param down_flag:
        :param key_list:
        :param obstacle_group:
        :return:
        """
        off_x = 0
        off_y = 0
        if self.count == 0:
            key = random.randint(0, 3)
            self.count = 3
            if key == 0:
                self.walk_action.set_dir(WalkDir.down)
                off_y += 10
            elif key == 1:
                self.walk_action.set_dir(WalkDir.up)
                off_y -= 10
            elif key == 2:
                self.walk_action.set_dir(WalkDir.left)
                off_x -= 10
            elif key == 3:
                self.walk_action.set_dir(WalkDir.right)
                off_x += 10
        else:
            self.count -= 1
        temp__rect = self.rect
        self.rect = self.rect.move(off_x, off_y)
        collidate_list = pygame.sprite.spritecollide(self, obstacle_group, False)
        if len(collidate_list) > 0:
            self.rect = temp__rect
        else:
            self.pos_x += off_x
            self.pos_y += off_y

    def draw(self, surface: pygame.Surface, x: int, y: int):
        """
        绘制移动战士
        :param surface:
        :param x:
        :param y:
        :return:
        """
        current_image = self.walk_action.get_image()
        surface.blit(current_image, (self.pos_x - x, self.pos_y - y))
        rect_x, rect_y, w, h = self.rect
        pygame.draw.rect(surface, pygame.Color(255, 0, 0), (rect_x - x, rect_y - y, w, h), 1)
